package com.wjjun.basemvpvm.data.observer;

import com.google.gson.JsonSyntaxException;
import com.google.gson.stream.MalformedJsonException;
import com.wjjun.basemvpvm.data.exception.MyException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.SocketTimeoutException;

import io.reactivex.observers.DisposableObserver;
import retrofit2.HttpException;

/**
 * Default {@link DisposableObserver} base class to be used whenever you want default error handling.
 */
public abstract class DefaultObserver<T> extends DisposableObserver<T> {

    @Override
    public void onNext(T t) {
        // no-op by default.
    }

    @Override
    public void onComplete() {
        // no-op by default.
    }

    public abstract void onError(MyException e);

    @Override
    public final void onError(Throwable exception) {
        if (exception instanceof SocketTimeoutException) {
            onError(new MyException(MyException.ERROR_CODE_SOCKET_TIMEOUT, "连接超时"));
        } else if (exception instanceof ConnectException) {
            onError(new MyException(MyException.ERROR_CODE_CONNECT, "连接出错"));
        } else if (exception instanceof HttpException) {
            onError(new MyException(MyException.ERROR_CODE_HTTP_REASON, "服务器错误"));
        } else if (exception instanceof JsonSyntaxException) {
            onError(new MyException(MyException.ERROR_CODE_DATA_PARSE, "数据解析出错"));
        } else if (exception instanceof MalformedJsonException) {
            onError(new MyException(MyException.ERROR_CODE_MALFORMED_JSON, "JSON解析出错"));
        } else if (exception instanceof SocketException) {
            onError(new MyException(MyException.ERROR_CODE_SOCKET, "连接错误"));
        } else if (exception instanceof MyException) {
            onError((MyException) exception);
        } else {
            onError(new MyException(MyException.ERROR_CODE_UN_KNOW, "未知错误"));
        }
        exception.printStackTrace();
    }
}
